package com.utcook.host.fragmentdialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.Observable
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.FragmentBurnerBinding

class BurnerFragment : Fragment() {

    private var _binding: FragmentBurnerBinding? = null
    private val binding get() = _binding!!
    
    private var burnerIndex: Int = 0
    private var burnerViewModel: BurnerViewModel? = null
    private var updateTimer: android.os.Handler? = null
    
    companion object {
        fun newInstance(index: Int, viewModel: BurnerViewModel): BurnerFragment {
            val fragment = BurnerFragment()
            fragment.burnerIndex = index
            fragment.burnerViewModel = viewModel
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentBurnerBinding.inflate(inflater, container, false)
        
        setupBurnerCard()
        setupStateListener()
        startUpdateTimer()
        
        return binding.root
    }
    
    private fun setupBurnerCard() {
        burnerViewModel?.let { viewModel ->
            binding.burner = viewModel.burners[burnerIndex]
            binding.isSelected = burnerIndex == viewModel.selectedBurnerIndex.get()
            binding.fragment = this
            
            // 获取烹饪状态
            val cookingState = viewModel.getBurnerCookingState(burnerIndex)
            binding.isCooking = cookingState?.isCooking ?: false
            binding.isPaused = cookingState?.isPaused ?: false
            binding.remainingSeconds = cookingState?.remainingSeconds ?: 0
            
            // 获取当前步骤文案
            val currentStepDescription = getCurrentStepDescription(cookingState)
            binding.currentStepDescription = currentStepDescription
            
            binding.executePendingBindings()
            
            // 设置CardView的selected状态
            binding.root.isSelected = binding.isSelected ?: false
            
            // 设置边框效果
            if (binding.isSelected == true) {
                binding.root.elevation = 12f
            } else {
                binding.root.elevation = 2f
            }
            
            binding.root.setOnClickListener {
                viewModel.selectBurner(burnerIndex)
            }
        }
    }
    
    private fun setupStateListener() {
        burnerViewModel?.selectedBurnerIndex?.addOnPropertyChangedCallback(
            object : Observable.OnPropertyChangedCallback() {
                override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                    updateBurnerState()
                }
            }
        )
    }
    
    fun updateBurnerState() {
        if (_binding == null) return
        
        burnerViewModel?.let { viewModel ->
            binding.burner = viewModel.burners[burnerIndex]
            binding.isSelected = burnerIndex == viewModel.selectedBurnerIndex.get()
            binding.fragment = this
            
            // 获取烹饪状态
            val cookingState = viewModel.getBurnerCookingState(burnerIndex)
            binding.isCooking = cookingState?.isCooking ?: false
            binding.isPaused = cookingState?.isPaused ?: false
            binding.remainingSeconds = cookingState?.remainingSeconds ?: 0
            
            // 获取当前步骤文案
            val currentStepDescription = getCurrentStepDescription(cookingState)
            binding.currentStepDescription = currentStepDescription
            
            android.util.Log.d("BurnerFragment", "炉头${burnerIndex + 1}更新状态: isCooking=${binding.isCooking}, isPaused=${binding.isPaused}, remainingSeconds=${binding.remainingSeconds}, stepDescription='${binding.currentStepDescription}'")
            
            binding.executePendingBindings()
            
            // 设置CardView的selected状态
            binding.root.isSelected = binding.isSelected ?: false
            
            // 设置边框效果
            if (binding.isSelected == true) {
                binding.root.elevation = 12f
            } else {
                binding.root.elevation = 2f
            }
            
            // 强制刷新背景
            binding.root.invalidate()
        }
    }
    
    fun onPauseButtonClick() {
        burnerViewModel?.let { viewModel ->
            viewModel.togglePauseCookingOnBurner(burnerIndex)
            // 更新按钮状态
            updateBurnerState()
        }
    }
    
    fun onStopButtonClick() {
        burnerViewModel?.let { viewModel ->
            // 停止烹饪
            viewModel.stopCookingOnBurner(burnerIndex)
            // 重置当前炉头的烹饪状态
            viewModel.resetBurnerCookingState(burnerIndex)
            // 更新按钮状态
            updateBurnerState()
            
            // 通知父Fragment返回菜谱操作页面
            (parentFragment as? RecipeFragment)?.showRecipeOperation()
        }
    }
    
    private fun startUpdateTimer() {
        updateTimer?.removeCallbacksAndMessages(null)
        updateTimer = android.os.Handler(android.os.Looper.getMainLooper())
        
        val updateRunnable = object : Runnable {
            override fun run() {
                updateBurnerState()
                updateTimer?.postDelayed(this, 1000)
            }
        }
        
        updateTimer?.post(updateRunnable)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        updateTimer?.removeCallbacksAndMessages(null)
        updateTimer = null
        _binding = null
    }

    private fun getCurrentStepDescription(cookingState: BurnerViewModel.BurnerCookingState?): String {
        val result = if (cookingState?.isCooking == true && cookingState.currentRecipe != null) {
            val currentStepIndex = cookingState.currentStepIndex
            val steps = cookingState.currentRecipe?.steps
            if (steps != null && currentStepIndex < steps.size) {
                steps[currentStepIndex].description
            } else {
                "步骤信息获取中..."
            }
        } else {
            ""
        }
        
        android.util.Log.d("BurnerFragment", "炉头${burnerIndex + 1}当前步骤文案: '$result', isCooking=${cookingState?.isCooking}, currentStepIndex=${cookingState?.currentStepIndex}, recipe=${cookingState?.currentRecipe?.name}")
        return result
    }
} 